<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
    
    protected $_id;
    
    public function setId($id)
    {
        if(isset($id{0}))
            $this->_id = $id;
        else
            throw new CException('The ID cann\'t be empty');
    }
    
    public function getId()
    {
        return $this->_id;
    }
    
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		$username = trim($this->username);
        
        $criteria = new EMongoCriteria;
        $criteria->setLimit(1);
        $criteria->setConditions(array(
            '$or'=>array(
                array('number'=>$username),
                array('fullname'=>$username),
            ),
        ));
        
        $user = User::model()->find($criteria);
        if(empty($user))
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		elseif($user->password != User::encryptPassword($this->password))
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
        {
            $this->setId($user->getId());
            $this->errorCode=self::ERROR_NONE;
        }
			
		return ! $this->errorCode;
	}
    
    /**
     * get identity by User model use for login after create user 
     * @param User $user
     * @return UserIdentity 
     */
    static public function getByUser(User $user)
    {
        $identity = new UserIdentity($user->email, $user->password);
        $identity->errorCode = self::ERROR_NONE;
        $identity->setId($user->getId());
        return $identity;
    }
}